<script setup>
import { getCurrentInstance, onBeforeUnmount, onMounted, ref } from "vue";
import { getToken } from "@/utils/auth";
import { getColumnByCode, updColumn } from "@/api/config/column";
import Editor from "@/components/RichText/index.vue";
const { proxy } = getCurrentInstance();
import emitter from "@/utils/mitt";

const props = defineProps({
	rowId: {
		type: [Number, String],
		default: null,
	},
	rowCode: {
		type: String,
		default: null,
	},
});

const formData = ref({
	// 内容代码
	code: "",
	// 内容内容
	content: "",
	// 内容表-主键id
	id: null,
	// 是否展示
	isView: 1,
	// 富文本文件
	richFileIds: [],
	// 内容标题
	title: "",
	// 标题图片
	coverFileIds: [],
});
const rules = ref({
	title: [{ required: true, message: "请输入内容标题", trigger: "blur" }],
});

const uploadFirstPicRef = ref(null);
const fileRichAction = import.meta.env.VITE_APP_BASE_API + "/columnContent/addRichFile";
const fileCoverAction = import.meta.env.VITE_APP_BASE_API + "/columnContent/addCoverImg";

const coverFilesData = ref([]);
const richFilesData = ref([]);

const removeFirstPic = () => {
	formData.value.coverFileIds = [];
	coverFilesData.value = [];
	proxy.$refs["uploadFirstPicRef"].clearFiles();
};
const uploadFirstPic = (response, file, fileList) => {
	if (response.code === 200) {
		formData.value.coverFileIds = [response.data.id];
		coverFilesData.value = [response.data];
		proxy.$refs["uploadFirstPicRef"].clearFiles();
	}
};
const clearFirstPic = () => {
	formData.value.coverFileIds = [];
	coverFilesData.value = [];
	proxy.$refs["uploadFirstPicRef"].clearFiles();
};

const getFormData = () => {
	const tempElement = document.createElement("div");
	formData.value.content = proxy.$refs["editorRef"].getCurrentValue();
	tempElement.innerHTML = formData.value.content;
	console.log(tempElement.innerHTML, "tempElement.innerHTML");
	console.log(richFilesData.value, "richFilesData.value");
	const imgElements = tempElement.querySelectorAll("img");
	formData.value.richFileIds = [];
	if (imgElements.length > 0) {
		imgElements.forEach((item) => {
			if (richFilesData.value.length) {
				let itemTemp = richFilesData.value.find((file) => file.accessUrl === item.currentSrc);
				formData.value.richFileIds.push(itemTemp.id);
			}
		});
	}
	return formData.value;
};

const getData = async () => {
	const res = await getColumnByCode({ code: props.rowCode });
	try {
		if (res.code === 200) {
			const { content, id, isView, outline, code, richFiles, title, coverFiles } = res.data;
			coverFilesData.value = coverFiles;
			richFilesData.value = richFiles;
			formData.value.content = content;
			formData.value.id = id;
			formData.value.isView = isView;
			formData.value.code = code;
			formData.value.title = title;
			formData.value.coverFileIds = coverFiles.map((item) => item.id);
			formData.value.richFileIds = richFiles.map((item) => item.id);
		}
	} catch (e) {
		console.log(e);
	}
};

// 提交
const submit = () => {
	proxy.$refs.elForm.validate(async (valid) => {
		if (valid) {
			const res = await updColumn(getFormData());
			try {
				if (res.code === 200) {
					proxy.$modal.msgSuccess("操作成功");
					cancel(true);
				} else {
					proxy.$modal.msgError(res.msg);
				}
			} catch (e) {
				console.log(e);
				proxy.$modal.msgError(JSON.stringify(e));
			}
		}
	});
};

const cancel = (ifSubmit = false) => {
	emitter.emit("closeEdit", ifSubmit);
};

onMounted(() => {
	if (props.rowId) {
		getData();
	}
	emitter.on("richTestFileList", (data) => {
		richFilesData.value = [...richFilesData.value, ...data];
		console.log(richFilesData.value);
	});
});

onBeforeUnmount(() => {
	emitter.off("richTestFileList");
});
</script>

<template>
	<div class="dialogContent">
		<el-form ref="elForm" :model="formData" :rules="rules" label-width="80px" style="width: calc(100% - 20px)">
			<el-form-item label="内容标题" prop="title" required>
				<el-input v-model="formData.title" clearable placeholder="请输入内容标题"></el-input>
			</el-form-item>
			<el-form-item label="封面图片">
				<el-upload
					ref="uploadFirstPicRef"
					:accept="'.jpg,.jpeg,.png'"
					:action="fileCoverAction"
					:headers="{
						Authorization: 'Bearer ' + getToken(),
					}"
					:limit="1"
					:on-remove="removeFirstPic"
					:on-success="uploadFirstPic"
					:show-file-list="false">
					<el-button size="small" type="primary">点击上传</el-button>
					<el-button size="small" type="warning" @click.stop="clearFirstPic">清空上传</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item v-if="coverFilesData.length > 0" prop="coverFileIds">
				<el-image :preview-src-list="[coverFilesData[0].accessUrl]" :src="coverFilesData[0].accessUrl" style="width: 100px; height: 100px">
				</el-image>
			</el-form-item>
			<el-form-item label="详细内容" prop="content">
				<Editor
					v-model="formData.content"
					:value="formData.content"
					:file-size="20"
					:max-height="360"
					:min-height="360"
					:url="'/columnContent/addRichFile'"
					style="width: 100%"
					ref="editorRef" />
			</el-form-item>
			<el-form-item label="是否隐藏" prop="isView">
				<el-switch v-model="formData.isView" :active-value="1" :inactive-value="0" active-text="显示" inactive-text="隐藏"></el-switch>
			</el-form-item>
		</el-form>
		<div class="buttonList">
			<el-button class="button" type="primary" @click="submit">提交</el-button>
			<el-button class="button" @click="cancel">取消</el-button>
		</div>
	</div>
</template>

<style lang="scss" scoped>
.dialogContent {
	overflow: auto;
}
.buttonList {
	display: flex;
	justify-content: center;
	margin-top: 20px;
}
</style>
